﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

public static class CollectionExtensions<T>
{
    #region Converting ObjectArray to Datatable
    public static DataTable ConvertToDataTable(IEnumerable<T> array, string tableName)
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        DataTable dt = CreateDataTable(properties, tableName);
        if (array.Count() != 0)
        {
            foreach (T o in array)
                FillData(properties, dt, o);
        }
        return dt;
    }

    private static DataTable CreateDataTable(PropertyInfo[] properties, string tableName)
    {
        DataTable dt = new DataTable(tableName);
        DataColumn dc = null;
        foreach (PropertyInfo pi in properties)
        {
            Type pt = pi.PropertyType;
            if (pt.Name == typeof(Nullable<>).Name)
            {
                pt = Nullable.GetUnderlyingType(pt);
            }
            dc = new DataColumn();
            dc.ColumnName = pi.Name;
            dc.DataType = pt;
            dt.Columns.Add(dc);
        }
        return dt;
    }

    private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
    {
        DataRow dr = dt.NewRow();
        foreach (PropertyInfo pi in properties)
        {
            dr[pi.Name] = pi.GetValue(o, null);
        }
        dt.Rows.Add(dr);
    }

    #endregion
}